package com.intelligent.controller;

import com.intelligent.annotation.OperationLog;
import com.intelligent.dto.ForgotPasswordDTO;
import com.intelligent.dto.LoginDTO;
import com.intelligent.dto.SmsCodeLoginDTO;
import com.intelligent.dto.SmsCodeSendDTO;
import com.intelligent.service.UserService;
import com.intelligent.utils.Result;
import com.intelligent.vo.LoginVO;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("login")
public class LoginController {
    @Resource
    private UserService userService;


//    @OperationLog(
//    module = "采购管理",
//    content = "'采购入库，数量=' + #count + '，产品名称=' + #productName"
//)
    @PostMapping
    @OperationLog(module = "登录模块", content = "'用户登录系统，账号：' + #loginDTO.username")
    public Result<LoginVO> login(@RequestBody LoginDTO loginDTO) {
        // @Validated 触发参数校验（如用户名/密码不能为空），校验失败会自动返回400错误
        LoginVO login = userService.login(loginDTO);
        return Result.success("登录成功", login);
    }

    // 发送验证码接口
    @PostMapping("/send-code")
    public Result<String> sendSmsCode(@Validated @RequestBody SmsCodeSendDTO sendDTO) {
        String smsCode = userService.sendSmsCode(sendDTO);
        return Result.success("发送成功");
    }

    /**
     * 验证码登录接口
     */
    @PostMapping("/phoneLogin")
    public Result<LoginVO> smsLogin(@Validated @RequestBody SmsCodeLoginDTO loginDTO) {
        LoginVO loginVO = userService.smsCodeLogin(loginDTO);
        return Result.success("登录成功", loginVO);
    }

    /**
     * 修改密码接口
     */
    @PostMapping("/updatePsaaword")
    public Result<String> updatePassword(@RequestBody ForgotPasswordDTO passwordDTO) {
        userService.updatePassword(passwordDTO);
        return Result.success("修改成功");
    }

    /**
     * 修改本人手机号（需登录）
     */
    @PostMapping("/updatePhone")
    public Result<String> updatePhone(@RequestAttribute(value = "CURRENT_USER_ID", required = false) Long userId,
            @Validated @RequestBody SmsCodeLoginDTO dto,
            HttpServletRequest request,
            @RequestHeader(value = "Authorization", required = false) String authorization,
            @RequestHeader(value = "X-Token", required = false) String xToken) {
        // Fallback: if interceptor didn't set CURRENT_USER_ID, try to parse from
        // headers
        if (userId == null) {
            String token = null;
            if (authorization != null && authorization.trim().length() > 0) {
                String a = authorization.trim();
                if (a.regionMatches(true, 0, "Bearer ", 0, 7)) {
                    token = a.substring(7).trim();
                } else {
                    token = a;
                }
            }
            if ((token == null || token.isEmpty()) && xToken != null && !xToken.trim().isEmpty()) {
                token = xToken.trim();
            }
            if ((token == null || token.isEmpty()) && request.getCookies() != null) {
                for (javax.servlet.http.Cookie c : request.getCookies()) {
                    if ("token".equalsIgnoreCase(c.getName())) {
                        token = c.getValue();
                        break;
                    }
                }
            }
            if (token != null && !token.isEmpty()) {
                Long uid = com.intelligent.security.JwtUtil.getUserId(token);
                if (uid != null) {
                    userId = uid;
                }
            }
            if (userId == null) {
                return Result.error(401, "未提供令牌或令牌无效");
            }
        }
        // dto.phone = 新手机号，dto.code = 新手机号收到的验证码
        userService.updatePhone(userId, dto);
        return Result.success("修改成功");
    }
}
